# ------------------------------------------------------------------------
# -*- coding: utf-8 -*-
# @Time    : 2022/9/12 16:44
# @Author  : Leii
# @File    : petri_net_AGV.py
# @Code instructions:petri网小作业
# ------------------------------------------------------------------------
import numpy as np
from random import randint

word = ["生产者1号触发生产", "生产者1号进入车间生产", "生产者1号生产完毕,准备离场", "AGV触发取货", "AGV进入取货区", "AGV取货完毕，准备离场"]


class Petri():
    def __init__(self, m0, pre, post):
        self.pre = pre
        self.post = post
        self.m0 = m0
        self.m = self.m0
        self.T = []
        self.p = []

    def is_enabled(self, Transition):  # 判断该变迁是否可以激发
        return np.all(Transition >= 0)

    def is_Transition(self):  # 当前状态下可以激发的变迁
        t_now = []
        for i in range(0, len(self.pre.T)):  # range(self.pre.shape[1])
            if i in self.p and len(self.p) < len(self.pre.T):
                continue
            elif len(self.p) == len(self.pre.T):
                self.p = []
            else:
                Transition = self.m - self.pre.T[i]  # self.pre[:, i]
                t_now.append(Transition)
                if self.is_enabled(Transition):
                    self.T.append(i)
                    self.p.append(i)
            # print("可激发的变迁有:" + str(self.T) + ".")
        if not self.T:
            return False
        else:
            print("可激发的变迁有:" + str(self.T) + ".")
            return True

    def update_m(self):  # 更新当前的标识
        if self.is_Transition():
            for item in self.T:
                self.m = self.post.T[item] - self.pre.T[item] + self.m
                print("我是当前", self.m)
                print(f"当前进行的变迁：{word[item]}\n")
            self.T = []
            return True
        else:
            print("不可激发")
            self.T = []
            return False


m0 = np.array([0, 0, 1, 3, 1, 0, 0, 0, 1])

pre = np.array([[0, 1, 0, 0, 0, 0],  # p1
                [0, 0, 1, 0, 0, 0],  # p2
                [1, 0, 0, 1, 0, 0],  # p3
                [1, 0, 0, 0, 0, 0],  # p4
                [0, 1, 0, 0, 1, 0],  # p5
                [0, 0, 0, 1, 0, 0],  # p6
                [0, 0, 0, 0, 1, 0],  # p7
                [0, 0, 0, 0, 0, 1],  # p8
                [0, 0, 0, 1, 0, 0]])  # p9

post = np.array([[1, 0, 0, 0, 0, 0],  # p1
                 [0, 1, 0, 0, 0, 0],  # p2
                 [0, 0, 1, 0, 0, 1],  # p3
                 [0, 0, 0, 0, 0, 1],  # p4
                 [0, 0, 1, 0, 0, 1],  # p5
                 [0, 0, 1, 0, 0, 0],  # p6
                 [0, 0, 0, 1, 0, 0],  # p7
                 [0, 0, 0, 0, 1, 0],  # p8
                 [0, 0, 0, 0, 0, 1]])  # p9

my_petri = Petri(m0, pre, post)
print("该petri网的初始标识：" + str(my_petri.m0))
# for i in range(20):
while True:
    my_petri.update_m()
